<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>K线图表 - 事件合约交易平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 100%;
            margin: 0;
            background: white;
            min-height: 100vh;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .header-left .logo {
            font-size: 1.8em;
        }
        
        .header-left h1 {
            font-size: 1.4em;
            font-weight: 700;
        }
        
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        
        .nav-btn {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 0.9em;
        }
        
        .nav-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-1px);
        }
        
        .price-ticker {
            background: white;
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 30px;
            flex-wrap: wrap;
        }
        
        .price-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
        }
        
        .price-label {
            font-size: 0.8em;
            color: #6c757d;
            font-weight: 500;
        }
        
        .price-value {
            font-size: 1.2em;
            font-weight: 600;
            color: #495057;
        }
        
        .price-change {
            font-size: 0.9em;
            font-weight: 500;
            padding: 2px 6px;
            border-radius: 4px;
        }
        
        .price-change.positive {
            color: #28a745;
            background: rgba(40, 167, 69, 0.1);
        }
        
        .price-change.negative {
            color: #dc3545;
            background: rgba(220, 53, 69, 0.1);
        }
        
        .chart-controls {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .control-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .control-group label {
            font-weight: 500;
            color: #495057;
            font-size: 0.9em;
        }
        
        .control-select {
            padding: 6px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 0.9em;
            background: white;
            cursor: pointer;
            outline: none;
        }
        
        .control-select:focus {
            border-color: #4facfe;
            box-shadow: 0 0 0 2px rgba(79, 172, 254, 0.2);
        }
        
        .refresh-btn {
            background: #4facfe;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9em;
            transition: all 0.3s ease;
        }
        
        .refresh-btn:hover {
            background: #2e86de;
            transform: translateY(-1px);
        }
        
        .refresh-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
        }
        
        .connection-status {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-left: auto;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #dc3545;
            animation: pulse 2s infinite;
        }
        
        .status-indicator.connected {
            background: #28a745;
        }
        
        .status-text {
            font-size: 0.85em;
            color: #6c757d;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .chart-container {
            flex: 1;
            position: relative;
            background: white;
            overflow: hidden;
        }
        
        .chart-wrapper {
            width: 100%;
            height: 100%;
            position: relative;
        }
        
        #klineChart {
            width: 100%;
            height: 100%;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4facfe;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            margin-top: 15px;
            color: #495057;
            font-size: 0.9em;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 12px 20px;
            border-left: 4px solid #dc3545;
            margin: 20px;
            border-radius: 4px;
            display: none;
        }
        
        .chart-info {
            background: #f8f9fa;
            padding: 10px 20px;
            border-top: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.85em;
            color: #6c757d;
        }
        
        @media (max-width: 768px) {
            .chart-controls {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .connection-status {
                margin-left: 0;
                margin-top: 10px;
            }
            
            .price-ticker {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
            
            .price-ticker > div {
                display: flex;
                flex-direction: row;
                gap: 15px;
                width: 100%;
            }
            
            .chart-container {
                /* 移动端使用flex布局自动调整高度 */
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部导航 -->
        <div class="header">
            <div class="header-left">
                <span class="logo">📈</span>
                <h1>K线图表</h1>
            </div>
            <div class="nav-buttons">
                <a href="index.html" class="nav-btn">🏠 主页</a>
                <button class="nav-btn" onclick="toggleFullscreen()">⛶ 全屏</button>
            </div>
        </div>
        
        <!-- 价格快显 -->
        <div class="price-ticker">
            <div class="price-item">
                <div class="price-label">当前价格</div>
                <div class="price-value" id="current-price">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h变化</div>
                <div class="price-change" id="price-change">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h高</div>
                <div class="price-value" id="price-high">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h低</div>
                <div class="price-value" id="price-low">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">开盘价</div>
                <div class="price-value" id="open-price">--</div>
            </div>
        </div>
        
        <!-- 图表控制 -->
        <div class="chart-controls">
            <div class="control-group">
                <label for="symbol-select">交易对:</label>
                <select id="symbol-select" class="control-select">
                    <option value="ETHUSDT">ETH/USDT</option>
                    <option value="BTCUSDT">BTC/USDT</option>
                </select>
            </div>
            
            <div class="control-group">
                <label for="interval-select">时间周期:</label>
                <select id="interval-select" class="control-select">
                    <option value="1m">1分钟</option>
                    <option value="5m">5分钟</option>
                    <option value="15m">15分钟</option>
                    <option value="1h" selected>1小时</option>
                    <option value="4h">4小时</option>
                    <option value="1d">1天</option>
                </select>
            </div>
            
            <button id="refresh-btn" class="refresh-btn" onclick="refreshChart()">
                🔄 刷新
            </button>
            
            <button class="refresh-btn" onclick="resizeChart()" style="background: #28a745;">
                📏 调整大小
            </button>
            
            <div class="connection-status">
                <div class="status-indicator" id="status-indicator"></div>
                <span class="status-text" id="status-text">连接中...</span>
            </div>
        </div>
        
        <!-- 错误消息 -->
        <div class="error-message" id="error-message"></div>
        
        <!-- 图表容器 -->
        <div class="chart-container">
            <div class="chart-wrapper">
                <canvas id="klineChart"></canvas>
                <div class="loading-overlay" id="loading-overlay">
                    <div class="loading-spinner"></div>
                    <div class="loading-text">正在加载K线数据...</div>
                </div>
            </div>
        </div>
        
        <!-- 图表信息 -->
        <div class="chart-info">
            <span id="chart-info-left">数据来源: 币安指数价格</span>
            <span id="chart-info-right">最后更新: --</span>
        </div>
    </div>

    <!-- Chart.js 库 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/date-fns@2.29.3/index.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@2.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

    <script>
        // 全局变量
        let chart = null;
        let websocket = null;
        let currentSymbol = 'ETHUSDT';
        let currentInterval = '1h';
        let isConnected = false;
        let klineData = [];
        let lastUpdateTime = null;
        let isLoading = false;
        
        // DOM元素
        const symbolSelect = document.getElementById('symbol-select');
        const intervalSelect = document.getElementById('interval-select');
        const refreshBtn = document.getElementById('refresh-btn');
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const errorMessage = document.getElementById('error-message');
        const loadingOverlay = document.getElementById('loading-overlay');
        const currentPrice = document.getElementById('current-price');
        const priceChange = document.getElementById('price-change');
        const priceHigh = document.getElementById('price-high');
        const priceLow = document.getElementById('price-low');
        const openPrice = document.getElementById('open-price');
        const chartInfoRight = document.getElementById('chart-info-right');
        
        // 初始化Chart.js图表
        function initChart() {
            const canvas = document.getElementById('klineChart');
            const ctx = canvas.getContext('2d');
            
            // 确保canvas尺寸正确
            const container = canvas.parentElement;
            canvas.width = container.clientWidth;
            canvas.height = container.clientHeight;
            
            chart = new Chart(ctx, {
                type: 'line',
                data: {
                    datasets: [{
                        label: `${currentSymbol} 价格`,
                        data: [],
                        borderColor: '#4facfe',
                        backgroundColor: 'rgba(79, 172, 254, 0.1)',
                        fill: true,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit: getTimeUnit(currentInterval),
                                displayFormats: {
                                    minute: 'HH:mm',
                                    hour: 'MM-dd HH:mm',
                                    day: 'MM-dd'
                                }
                            },
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '价格 (USDT)'
                            },
                            position: 'right'
                        }
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                title: function(context) {
                                    const date = new Date(context[0].parsed.x);
                                    return date.toLocaleString('zh-CN');
                                },
                                label: function(context) {
                                    const data = context.raw;
                                    return [
                                        `开盘: ${data.o}`,
                                        `最高: ${data.h}`,
                                        `最低: ${data.l}`,
                                        `收盘: ${data.c}`
                                    ];
                                }
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        }
        
        // 获取时间单位
        function getTimeUnit(interval) {
            const unitMap = {
                '1m': 'minute',
                '5m': 'minute',
                '15m': 'minute',
                '1h': 'hour',
                '4h': 'hour',
                '1d': 'day'
            };
            return unitMap[interval] || 'hour';
        }
        
        // 简化的线图实现，避免复杂的candlestick错误
        
        // 获取K线数据
        async function fetchKlineData(symbol, interval, limit = 500) {
            try {
                setLoading(true);
                
                // 构建币安API URL
                const baseUrl = 'https://fapi.binance.com/fapi/v1/indexPriceKlines';
                const params = new URLSearchParams({
                    pair: symbol,
                    interval: interval,
                    limit: limit.toString()
                });
                
                const url = `${baseUrl}?${params}`;
                console.log('获取K线数据:', url);
                
                // 使用代理或CORS代理来避免跨域问题
                const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;
                
                const response = await fetch(proxyUrl);
                const result = await response.json();
                
                if (result.status && result.status.http_code === 200) {
                    const data = JSON.parse(result.contents);
                    return parseKlineData(data);
                } else {
                    throw new Error('API请求失败');
                }
                
            } catch (error) {
                console.error('获取K线数据失败:', error);
                showError('获取K线数据失败，使用模拟数据');
                // 返回模拟数据
                return generateMockKlineData(symbol, interval, limit);
            } finally {
                setLoading(false);
            }
        }
        
        // 解析币安K线数据，转换为简单的价格点
        function parseKlineData(binanceData) {
            return binanceData.map(kline => ({
                x: parseInt(kline[0]), // 时间
                y: parseFloat(kline[4]) // 收盘价作为价格点
            }));
        }
        
        // 生成模拟价格数据
        function generateMockKlineData(symbol, interval, limit) {
            const data = [];
            const now = Date.now();
            const intervalMs = getIntervalMs(interval);
            const basePrice = symbol === 'ETHUSDT' ? 3800 : 50000;
            
            for (let i = limit - 1; i >= 0; i--) {
                const time = now - i * intervalMs;
                const price = basePrice + (Math.random() - 0.5) * basePrice * 0.05;
                
                data.push({
                    x: time,
                    y: parseFloat(price.toFixed(2))
                });
            }
            
            return data;
        }
        
        // 获取时间间隔毫秒数
        function getIntervalMs(interval) {
            const intervalMap = {
                '1m': 60 * 1000,
                '5m': 5 * 60 * 1000,
                '15m': 15 * 60 * 1000,
                '1h': 60 * 60 * 1000,
                '4h': 4 * 60 * 60 * 1000,
                '1d': 24 * 60 * 60 * 1000
            };
            return intervalMap[interval] || 60 * 60 * 1000;
        }
        
        // 更新图表数据
        function updateChart(data) {
            if (!chart || !data || data.length === 0) return;
            
            klineData = data;
            chart.data.datasets[0].data = data;
            chart.data.datasets[0].label = `${currentSymbol} K线 (${currentInterval})`;
            
            // 更新时间轴单位
            chart.options.scales.x.time.unit = getTimeUnit(currentInterval);
            
            chart.update('none'); // 无动画更新以提高性能
            
            // 更新价格信息
            updatePriceInfo(data);
            
            // 更新最后更新时间
            lastUpdateTime = new Date();
            chartInfoRight.textContent = `最后更新: ${lastUpdateTime.toLocaleTimeString('zh-CN')}`;
        }
        
        // 更新价格信息
        function updatePriceInfo(data) {
            if (!data || data.length === 0) return;
            
            const latest = data[data.length - 1];
            const first = data[0];
            
            // 计算24h高低价
            const high24h = Math.max(...data.map(d => d.y));
            const low24h = Math.min(...data.map(d => d.y));
            
            // 计算涨跌
            const priceChangeValue = latest.y - first.y;
            const priceChangePercent = ((priceChangeValue / first.y) * 100);
            
            // 更新显示
            currentPrice.textContent = latest.y.toFixed(2);
            priceHigh.textContent = high24h.toFixed(2);
            priceLow.textContent = low24h.toFixed(2);
            openPrice.textContent = first.y.toFixed(2);
            
            // 更新涨跌显示
            const changeText = `${priceChangeValue >= 0 ? '+' : ''}${priceChangeValue.toFixed(2)} (${priceChangePercent >= 0 ? '+' : ''}${priceChangePercent.toFixed(2)}%)`;
            priceChange.textContent = changeText;
            priceChange.className = `price-change ${priceChangeValue >= 0 ? 'positive' : 'negative'}`;
        }
        
        // 连接WebSocket
        function connectWebSocket() {
            try {
                const wsUrl = 'ws://localhost:8770';
                websocket = new WebSocket(wsUrl);
                
                websocket.onopen = () => {
                    console.log('WebSocket连接成功');
                    isConnected = true;
                    updateStatus(true, '已连接');
                    
                    // 获取价格数据
                    websocket.send(JSON.stringify({
                        action: 'get_prices'
                    }));
                };
                
                websocket.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        handleWebSocketMessage(data);
                    } catch (error) {
                        console.error('解析WebSocket消息失败:', error);
                    }
                };
                
                websocket.onclose = () => {
                    console.log('WebSocket连接断开');
                    isConnected = false;
                    updateStatus(false, '连接断开');
                    
                    // 自动重连
                    setTimeout(connectWebSocket, 3000);
                };
                
                websocket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    updateStatus(false, '连接错误');
                };
                
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                updateStatus(false, '连接失败');
            }
        }
        
        // 处理WebSocket消息
        function handleWebSocketMessage(data) {
            if (data.type === 'price_update') {
                updateRealtimePrice(data.data);
            } else if (data.prices) {
                // 初始价格数据
                const symbolData = data.prices[currentSymbol];
                if (symbolData) {
                    updateRealtimePrice(symbolData);
                }
            }
        }
        
        // 更新实时价格
        function updateRealtimePrice(priceData) {
            if (!priceData || priceData.s !== currentSymbol) return;
            
            const newPrice = parseFloat(priceData.p);
            if (newPrice === 0) return; // 忽略连接失败的0价格
            
            // 更新最新价格点
            if (klineData && klineData.length > 0) {
                const lastPoint = klineData[klineData.length - 1];
                const now = Date.now();
                
                // 如果是当前时间周期内，更新最新价格
                const intervalMs = getIntervalMs(currentInterval);
                const currentTimeStart = Math.floor(now / intervalMs) * intervalMs;
                
                if (lastPoint.x >= currentTimeStart - intervalMs) {
                    lastPoint.y = newPrice;
                    
                    // 更新图表
                    chart.update('none');
                    
                    // 更新价格显示
                    currentPrice.textContent = newPrice.toFixed(2);
                    
                    console.log(`更新实时价格: ${currentSymbol} = ${newPrice}`);
                }
            }
        }
        
        // 更新连接状态
        function updateStatus(connected, text) {
            statusIndicator.className = `status-indicator ${connected ? 'connected' : ''}`;
            statusText.textContent = text;
        }
        
        // 显示错误消息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }
        
        // 设置加载状态
        function setLoading(loading) {
            isLoading = loading;
            refreshBtn.disabled = loading;
            if (loading) {
                loadingOverlay.style.display = 'flex';
                refreshBtn.textContent = '⏳ 加载中...';
            } else {
                loadingOverlay.style.display = 'none';
                refreshBtn.textContent = '🔄 刷新';
            }
        }
        
        // 刷新图表
        async function refreshChart() {
            if (isLoading) return;
            
            console.log(`刷新图表: ${currentSymbol} ${currentInterval}`);
            
            try {
                const data = await fetchKlineData(currentSymbol, currentInterval);
                updateChart(data);
            } catch (error) {
                console.error('刷新图表失败:', error);
                showError('刷新失败，请稍后重试');
            }
        }
        
        // 切换全屏
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        }
        
        // 事件监听器
        symbolSelect.addEventListener('change', (e) => {
            currentSymbol = e.target.value;
            console.log('切换交易对到:', currentSymbol);
            refreshChart();
        });
        
        intervalSelect.addEventListener('change', (e) => {
            currentInterval = e.target.value;
            console.log('切换时间周期到:', currentInterval);
            refreshChart();
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            console.log('K线图表页面加载完成，开始初始化...');
            
            // 初始化图表
            initChart();
            
            // 强制调整图表大小
            setTimeout(() => {
                resizeChart();
            }, 500);
            
            // 连接WebSocket
            connectWebSocket();
            
            // 加载初始数据
            await refreshChart();
        });
        
        // 强制调整图表大小
        function resizeChart() {
            if (chart) {
                const canvas = document.getElementById('klineChart');
                const container = canvas.parentElement;
                
                // 强制重新计算尺寸
                canvas.style.width = '100%';
                canvas.style.height = '100%';
                
                // 调用Chart.js的resize方法
                chart.resize();
                
                console.log('图表已调整大小:', container.clientWidth, 'x', container.clientHeight);
            }
        }
        
        // 窗口大小调整时重新调整图表
        window.addEventListener('resize', () => {
            setTimeout(resizeChart, 100);
        });
        
        // 页面卸载时清理
        window.addEventListener('beforeunload', () => {
            if (websocket) {
                websocket.close();
            }
            if (chart) {
                chart.destroy();
            }
        });
    </script>
</body>
</html>
